package interview.lock;

import java.util.concurrent.Semaphore;

/**
 *   Semaphor的用法：与CountDownLatch,CyclicBarrier用法不同，CountDownLatch是倒计时,CyclicBarrier是达到某一数值,而Semaphore类似于停车，假设停车位有5
 *                  个停车位，而此时有10辆车.那么肯定有5辆车要等到其他车出来后才能停进去.
 *
 *
 * **/
public class SemaphoreDemo {
    public static void main(String[] args) {
        Semaphore semaphore = new Semaphore(5);
        for(int i=0;i<100;i++){
            new Thread(()->{
                try {
                    semaphore.acquire();
                    System.out.println(Thread.currentThread().getName()+"抢到车位");
                    Thread.sleep(3000);
                    System.out.println(Thread.currentThread().getName()+"停车三秒离开！");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }finally {
                    semaphore.release();
                }
            }).start();
        }
    }
}
